<?php 
namespace Admin\Controller;

use Admin\Model\Goods_classModel;
use Admin\Model\GoodsModel;

class GoodsController extends CommonController{

    public function index(){

        $rel = M('goods_list a')->field('a.*,b.name')->join('left join agency_goods_class b on a.class_id = b.class_id')->select();

        foreach($rel as $k=>$v){
            //处理json格式的属性
            $attribute =  json_decode($v['attribute']);
            foreach($attribute as $ks => $vs){
                $att = M('attribute_value a')->field('value')->where(array('attribute_id'=>$vs))->find();
                $atts = $atts .','.$att['value'];
            }
            $rel[$k]['attribute'] = $atts;
            $atts = '';

            //处理json格式的图片
            $imgs = json_decode($v['goods_img']);
            $rel[$k]['goods_img'] = $imgs[0];
        }

        $this->assign('list',$rel);
        $this->display();
    }

    public function add(){


        if(IS_POST){
            $data = I('post.');

            $map['class_id'] = I('post.class_id','',intval);
            $map['goods_name'] = I('post.goods_name','',trim);
            $map['attribute'] = json_encode(I('post.attribute'));
            $map['state'] = I('post.state');
            $map['vip_exclusive'] = I('post.vip_exclusive');
            $map['superior_user_integral'] = I('post.superior_user_integral');
            $map['supervisor_user_integral'] = I('post.supervisor_user_integral');
            $map['goods_intro'] = $_POST['goods_intro'];
            $map['insert_time'] = time();


            $img_count = count($_FILES['pic']['name']);

            $imgs='';
            if($_FILES['pic']['name'][0] != '') {

                for ($i = 0; $i < $img_count; $i++) {
                    //图片上传

                    /*if (!isset($_FILES['goods_img']) || $_FILES['goods_img']['error'] != 0) {
                        return false;
                    }*/

                    $maps['img'] = $_FILES['pic']['name'][$i];
                    $maps['type'] = $_FILES['pic']['type'][$i];
                    $maps['tmp_name'] = $_FILES['pic']['tmp_name'][$i];
                    $maps['size'] = $_FILES['pic']['size'][$i];


                    //实现图片上传
                    $upload = new \Think\Upload();
                    $info = $upload->uploadOne($maps);
                    if(!$info){
                        $this->error=$upload->getError();
                    }
                    //在代码中图片的地址使用不用使用/ 在html代码中显示图片时必须使用/ 表示域名对应的根目录
                    //上传之后的图片地址
                    $goods_img = 'Uploads/'.$info['savepath'].$info['savename'];
                    //实现缩略图的制作
                    $img = new \Think\Image();
                    //打开图片
                    $img->open($goods_img);
                    //制作缩略图
                    $goods_thumb = 'Uploads/'.$info['savepath'].'thumb_'.$info['savename'].'jpg';
                    $img->save($goods_thumb);
                    //返回图片地址
                    /*$imgs=array('goods_img'=>$goods_img,'goods_thumb'=>$goods_thumb);
                    $imgs[$i]['goods_img'] = $goods_img.'jpg';
                    $imgs[$i]['goods_thumb'] = $goods_thumb;*/

                    if ($img_count > 1) {
                        $imgs[$i] = "http://".$_SERVER['HTTP_HOST'].'/'.$goods_thumb;
                    } else {
                        $imgs = $goods_thumb;
                    }

                }

                $map['goods_img'] = json_encode($imgs);
            }

           $rel = M('goods_list')->add($map);
            //$rel = 1;
            if($rel){

                $counts = count($data['region_id']);

                for($j=0;$j<$counts;$j++) {

                    $area = $data['region_id'][$j];
                    //$normal = I('post.normal');
                    $price['goods_id'] = $rel;
                    $price['region_id'] = $area;
                    $price['normal'] = $data['normal'][$area];
                    $price['price'] =  $data['price'][$area];
                    $price['vip_discount'] = json_encode($data['vip_discount'][$area]);

                    $spec_name = $data['spec_name'][$area][0];
                    $values =$data['values'][$area];
                    $prices = $data['prices'][$area];
                    $integral_price = $data['integral_price'][$area];
                    $states = $data['states'][$area];
                    $spec['name'] = $spec_name;
                    $count = count($values);

                    for ($i = 0; $i < $count; $i++) {
                        $spec['option'][$i]['value'] = $values[$i];
                        $spec['option'][$i]['price'] = $prices[$i];
                        $spec['option'][$i]['integral_price'] = $integral_price[$i];
                        $spec['option'][$i]['states'] = $states[$i];
                    }
                    $price['spec'] = json_encode($spec);

                    M('goods_price')->add($price);
                }

                //详情添加
                $info['goods_id'] = $rel;
                if(!empty($_POST['goods_info'])) {
                    $info['goods_info'] = $_POST['goods_info'];
                }
                $info['seo_title'] = $data['seo_title'];
                $info['seo_keywords'] =  $data['seo_keywords'];
                $info['seo_description'] =  $data['seo_description'];
                $re = M('goods_info')->add($info);
                if($re){
                    // header("location: http://www.dzshop.net/Admin/Index/index.html");
                    $this->success("添加成功！",U("Goods/index"),1);
                }else{
                    $this->error("添加失败！");
                }

            }
            //die(json_encode(array('rel'=>$ff)));
        }

        $att = M('attribute_value a')->field('a.*,b.attribute_name')
            ->join('left join agency_attribute_name b on a.attribute_name_id = b.attribute_name_id')->select();

        $this->assign('att',$att);

        //售卖地区.暂默认ID1为售卖地区配置
        $area = M('sys_configure')->field('configure_value')->where(array('configure_id'=>1))->find();
        $area_id = json_decode($area['configure_value']);

        $ids = implode(',',$area_id);
        $ids =substr($ids,1);
        $mp['region_id']=array('in',$ids);
        $area = M('region_list')->field('region_id,region_name')->where($mp)->select();

        $this->assign('areas',$area);


        $cateM = new Goods_classModel();

        $goods_class = $cateM->getCateTree();
        $this->assign('goods_class',$goods_class);
        $this->display();
    }

    public function edit(){

        if(IS_POST){
            $data = I('post.');

            $map['class_id'] = I('post.class_id','',intval);
            $map['goods_name'] = I('post.goods_name','',trim);
            $map['attribute'] = json_encode(I('post.attribute'));
            $map['state'] = I('post.state');
            $map['vip_exclusive'] = I('post.vip_exclusive');
            $map['superior_user_integral'] = I('post.superior_user_integral');
            $map['supervisor_user_integral'] = I('post.supervisor_user_integral');
            $map['goods_intro'] = $_POST['goods_intro'];
            //$map['insert_time'] = time();


            $img_count = count($_FILES['pic']['name']);

            $imgs='';
            if($_FILES['pic']['name'][0] != '') {

                for ($i = 0; $i < $img_count; $i++) {
                    //图片上传

                    /*if (!isset($_FILES['goods_img']) || $_FILES['goods_img']['error'] != 0) {
                        return false;
                    }*/

                    $maps['img'] = $_FILES['pic']['name'][$i];
                    $maps['type'] = $_FILES['pic']['type'][$i];
                    $maps['tmp_name'] = $_FILES['pic']['tmp_name'][$i];
                    $maps['size'] = $_FILES['pic']['size'][$i];


                    //实现图片上传
                    $upload = new \Think\Upload();
                    $info = $upload->uploadOne($maps);
                    if(!$info){
                        $this->error=$upload->getError();
                    }
                    //在代码中图片的地址使用不用使用/ 在html代码中显示图片时必须使用/ 表示域名对应的根目录
                    //上传之后的图片地址
                    $goods_img = 'Uploads/'.$info['savepath'].$info['savename'];
                    //实现缩略图的制作
                    $img = new \Think\Image();
                    //打开图片
                    $img->open($goods_img);
                    //制作缩略图
                    $goods_thumb = 'Uploads/'.$info['savepath'].'thumb_'.$info['savename'].'jpg';
                    $img->save($goods_thumb);
                    //返回图片地址
                    /*$imgs=array('goods_img'=>$goods_img,'goods_thumb'=>$goods_thumb);
                    $imgs[$i]['goods_img'] = $goods_img.'jpg';
                    $imgs[$i]['goods_thumb'] = $goods_thumb;*/

                    if ($img_count > 1) {
                        $imgs[$i] = "http://".$_SERVER['HTTP_HOST'].'/'.$goods_thumb;
                    } else {
                        $imgs = $goods_thumb;
                    }

                }

                $map['goods_img'] = json_encode($imgs);
            }

            $rel = M('goods_list')->where(array('goods_id'=>$data['save_id']))->save($map);
            //$rel = 1;


                $counts = count($data['region_id']);

                for($j=0;$j<$counts;$j++) {

                    $area = $data['region_id'][$j];
                    //$normal = I('post.normal');
                    $price['goods_id'] = $data['save_id'];
                    $price['region_id'] = $area;
                    $price['normal'] = $data['normal'][$area];
                    $price['price'] =  $data['price'][$area];
                    $price['vip_discount'] = json_encode($data['vip_discount'][$area]);

                    $spec_name = $data['spec_name'][$area][0];
                    $values =$data['values'][$area];
                    $prices = $data['prices'][$area];
                    $integral_price = $data['integral_price'][$area];
                    $states = $data['states'][$area];
                    $spec['name'] = $spec_name;
                    $count = count($values);

                    for ($i = 0; $i < $count; $i++) {
                        $spec['option'][$i]['value'] = $values[$i];
                        $spec['option'][$i]['price'] = $prices[$i];
                        $spec['option'][$i]['integral_price'] = $integral_price[$i];
                        $spec['option'][$i]['states'] = $states[$i];
                    }
                    $price['spec'] = json_encode($spec);
                    $price['goods_id'] = $data['save_id'];
                    $price['region_id'] =$data['region_id'][$j];
                    $pr = M('goods_price')->where(array('goods_id'=>$data['save_id']))->find();
                    if(!empty($pr)){
                        M('goods_price')->where(array('goods_id'=>$data['save_id']))->save($price);
                    }else{
                        M('goods_price')->add($price);
                    }

                }



                //详情添加
                $info['goods_id'] = $data['save_id'];
                if(!empty($_POST['goods_info'])) {
                    $info['goods_info'] = $_POST['goods_info'];
                }
                $info['seo_title'] = $data['seo_title'];
                $info['seo_keywords'] =  $data['seo_keywords'];
                $info['seo_description'] =  $data['seo_description'];
               $info =  M('goods_info')->where(array('goods_id'=>$data['save_id']))->find();
            if(!empty($info)){
                 M('goods_info')->where(array('goods_id'=>$data['save_id']))->save($info);
            }else{
                M('goods_info')->add($info);
            }



                // header("location: http://www.dzshop.net/Admin/Index/index.html");
                $this->success("修改成功！", U("Goods/index"), 1);




        }

        $id = I('get.goods_id');
        $data = M('goods_list a')->field('b.name,c.*,d.*,a.*')->join('left join agency_goods_class b on a.class_id = b.class_id')
            ->join('left join agency_goods_info c on a.goods_id = c.goods_id')
            ->join('left join agency_goods_price d on a.goods_id = d.goods_id')
            ->where(array('a.goods_id'=>$id))->select();

        foreach($data as $dk => $dv){
            //所售卖地区
            $areas = M('region_list')->field('region_name')->where(array('region_id'=> $dv['region_id']))->find();
            $data[0]['areas'][] =  $areas['region_name'];


            $data[$dk]['goods_img']=json_decode($dv['goods_img']);
            $data[$dk]['attribute']=json_decode($dv['attribute']);

            foreach($data[$dk]['attribute'] as $tk =>$tv){
                $data[$dk]['attributes'][]=M('attribute_value')->where(array('attribute_id'=>$tv))->find();//物品属性
            }

            $data[$dk]['vip_discount']=(array)json_decode($dv['vip_discount']);
            $data[$dk]['spec']=(array)json_decode($dv['spec']);
            foreach( $data[$dk]['spec']['option'] as  $sck=>$scv){
                $data[$dk]['spec']['option'][$sck] = (array)$scv;
            }

        }


        $this->assign('data',$data);
//dump($data);die;


        $att = M('attribute_value a')/*->field('a.*,b.attribute_name')
            ->join('left join agency_attribute_name b on a.attribute_name_id = b.attribute_name_id')
            ->where(array('b.class_id'=>$data[0]['class_id']))*/->select();
        //dump($att);die;

        $this->assign('atts',$att);

        //售卖地区.暂默认ID1为售卖地区配置
        $area = M('sys_configure')->field('configure_value')->where(array('configure_id'=>1))->find();
        $area_id = json_decode($area['configure_value']);

        $ids = implode(',',$area_id);
        $ids =substr($ids,1);
        $mp['region_id']=array('in',$ids);
        $area = M('region_list')->field('region_id,region_name')->where($mp)->select();

        $this->assign('areas',$area);


        $cateM = new Goods_classModel();

        $goods_class = $cateM->getCateTree();
        $this->assign('goods_class',$goods_class);

        $this->display();
    }

    public function dels(){
        $id = I('get.goods_id');

            $map['state'] = 0;
            $rel = M('goods_list')->where(array('goods_id' => $id))->save($map);
            if ($rel) {
                // header("location: http://www.dzshop.net/Admin/Index/index.html");
                $this->success("删除成功！", U("Goods/index"), 1);
            } else {
                $this->error("删除失败！");
            }


    }

    public function price_list(){

    }

    public function price_add(){
        $this->display();
    }

/*    public function showAttr(){
        $type_id = intval(I('post.type_id'));
        if($type_id<=0){
            echo '没有数据';die;
        }
        $data=D('Attribute')->where('type_id='.$type_id)->select();
        foreach($data as $key=>$value){
            if($value['attr_input_type']==2){
                //是一个列表选择 因此需要处理默认值
                $data[$key]['attr_value']=explode(',',$value['attr_value']);
            }
        }
        foreach($attr as $key=>$value){
            $attr_list[$value['attr_id']][]=$value;
        }
        //dump($data);die;
        $this->assign("data",$data);
        $this->display();
    }

	public function add(){
		if(IS_GET){
            //获取所有的类型
            $type = D('Type')->select();
            $this->assign("type",$type);
			//获取所有的分类
			$cate = D('Category')->getCateTree();
			$this->assign('cate',$cate);
			$this->display();
			exit();
		}
		$model = D('Goods');
		$data = $model->create();
		if(!$data){
			$this->error($model->getError());
		}
		$goods_id = $model->add($data);
		if(!$goods_id){
			$this->error($model->getError());
		}
		$this->success('添加成功');
	}

    //商品列表展示
    public function index(){
        //获取分类信息
        $cate = D('Category')->getCateTree();
        $this->assign('cate',$cate);

        $model = D('Goods');
        //调用模型方法获取数据
        $data = $model->listData();
        $this->assign('data',$data);
        $this->display();
    }

    //回收站商品列表显示
    public function trash(){
        //获取分类信息
        $cate = D('Category')->getCateTree();
        $this->assign('cate',$cate);

        $model=D('Goods');
        //调用模型方法获取数据
        $data = $model->listData(0);
        $this->assign('data',$data);
        $this->display();
    }







    //修改
    public function edit(){
        if(IS_GET){
            $goods_id = intval(I('get.goods_id'));
            $model=D('Goods');
            $info = $model->findOneById($goods_id);
            if(!$info){
                $this->error('参数错误');
            }
            //获取所有的分类信息
            $cate = D('Category')->getCateTree();
            $this->assign('cate',$cate);

            //扩展分类获取
            $ext_cate_ids =M('GoodsCate')->where("goods_id=$goods_id")->select();
            if(!$ext_cate_ids){
                //对于没有扩展分类的商品手动追加一个元素
                $ext_cate_ids=array(
                    array('msg'=>'no data')
                );
            }
            $this->assign('ext_cate_ids',$ext_cate_ids);
            $info['goods_body']=htmlspecialchars_decode($info['goods_body']);
            $this->assign('info',$info);

            //获取所有的类型
            $type = D('Type')->select();
            $this->assign('type',$type);
            //根据商品标识获取当前商品对应的属性及属性值
            $goodsAttrModel = M('GoodsAttr');
            $attr=$goodsAttrModel->
            alias('a')->field('a.*,b.attr_name,b.attr_type,b.attr_input_type,b.attr_value')
                ->join('left join jx_attribute b on a.attr_id=b.id')->where('a.goods_id='.$goods_id)->select();
            foreach($attr as $key=>$value){
                if($value['attr_input_type']==2){
                    $attr[$key]['attr_value']=explode(',',$value['attr_value']);
                }
            }
            foreach($attr as $key=>$value){
                $attr_list[$value['attr_id']][]=$value;
            }
            //dump($attr_list);die;
            $this->assign('attr',$attr_list);
            //获取商品对应的相册图片信息
            $goods_img_list = D('GoodsImg')->where('goods_id='.$goods_id)->select();
            $this->assign('goods_img_list',$goods_img_list);

            $this->display();

        }else{
            $model=D('Goods');
            $data = $model->create();
            if(!$data){
                $this->error($model->getError());
            }
            $res = $model->update($data);
            if($res ===false){
                $this->error($model->getError());
            }
            $this->success('修改成功',U('index'));
        }
    }

    public function remove(){
        $goods_id=intval(I('get.goods_id'));
        if($goods_id<=0){
            $this->error('参数错误');
        }
        $model = D('Goods');
        $res=$model->remove($goods_id);
        if($res===false){
            $this->error('删除失败');
        }
        $this->success('删除成功');
    }

        //商品的伪删除
    public function dels(){
        $goods_id=intval(I('get.goods_id'));
        $model=D('Goods');
        $res=$model->setStatus($goods_id,0);
        if($res==false){
            $this->error('删除失败');
        }
        $this->success('删除成功');
    }

    //商品的还原
    public function recover(){
        $goods_id=intval(I('get.goods_id'));
        $model=D('Goods');
        $res=$model->setStatus($goods_id,1);
        if($res==false){
            $this->error('还原失败');
        }
        $this->success('还原成功');
    }

    //删除相册中的图片
    public function delImg(){
        //使用request目的是为了方便浏览器之间测试使用
        $img_id = intval(I('post.img_id'));
        $ImgModel = M('GoodsImg');
        $info = $ImgModel->where('id='.$img_id)->find();
        if(!$info){
            $this->ajaxReturn(array('status'=>0,'msg'=>'参数错误'));
        }
        //先将对应的图片信息删除掉
        unlink($info['goods_img']);
        unlink($info['goods_thumb']);
        //在将数据从数据库中删除
        $ImgModel->where('id='.$img_id)->delete();
        $this->ajaxReturn(array('status'=>1,'msg'=>'ok'));
    }

    //实现商品库存设置
    public function setNumber(){
        if(IS_GET){
            $goods_id=intval(I('get.goods_id'));
            //通过商品的标识获取对应的单选属性值及属性信息
            $GoodsAttrModel = D('GoodsAttr');
            $attr = $GoodsAttrModel->getSigleAttr($goods_id);
            if(!$attr){
                //针对没有单选属性的商品获取对应的库存信息
                $info=D('Goods')->where('id='.$goods_id)->find();
                $this->assign('info',$info);
                //该商品没有单选属性
                $this->display('nosigle');
                exit;
            }
            //针对有单选属性的库存信息获取
            $info =M('GoodsNumber')->where('goods_id='.$goods_id)->select();
            if(!$info){
                //没有获取到对应的库存信息，为了保证模板能够正常显示至少需要一次循环
                $info=array('goods_number'=>0);
            }
            $this->assign('info',$info);
            //dump($attr);die;
            $this->assign('attr',$attr);
            $this->display();
        }else{
            $attr = I('post.attr');
            $goods_number =I('post.goods_number');
            $goods_id=I('post.goods_id');

            if(!$attr){
                //没有单选属性数据的提交
                D('Goods')->where('id='.$goods_id)->setField('goods_number',$goods_number);
                exit;
            }
            //通过循环处理组合 最后数据入库
            foreach($goods_number as $key=>$value){
                //拼接处具体的组合信息
                $tmp=array();
                foreach($attr as $k=>$v){
                    $tmp[]=$v[$key];
                }
                //将组合的数组格式转换为字符串的格式
                sort($tmp);
                $goods_attr_ids=implode(',',$tmp);
                //实现组合的去重
                if(in_array($goods_attr_ids,$has)){
                    unset($goods_number[$key]);
                    continue;
                }
                $has[]=$goods_attr_ids;

                $list[]=array(
                    'goods_id'=>$goods_id,
                    'goods_number'=>$value,
                    'goods_attr_ids'=>$goods_attr_ids,
                );
            }

                //实现删除当前商品以及拥有的库存信息
                M('GoodsNumber')->where('goods_id='.$goods_id)->delete();
                //将库存信息入库
                M('GoodsNumber')->addAll($list);
                //计算当前库存总数
                $goods_count = array_sum($goods_number);
                D('Goods')->where('id='.$goods_id)->setField('goods_number',$goods_count);
                $this->success('库存量已经更新',U('index'));

        }
    }*/
}
